import Vue from 'vue'

import 'normalize.css/normalize.css' // A modern alternative to CSS resets

import ELEMENT from 'element-ui'
// import 'element-ui/lib/theme-chalk/index.css'
import enLocale from 'element-ui/lib/locale/lang/en' // lang i18n
import zhLocale from 'element-ui/lib/locale/lang/zh-CN' // lang i18n

import '@/styles/index.scss' // global css

import App from './App'
import store from './store'
import router from './router'

import '@/icons' // icon
import '@/permission' // permission control

import { extend, parseTime } from '@/utils'

import SignalRAspNetCoreHelper from './vendor/abp/SignalRAspNetCoreHelper'
// import SignalRHelper from './libs/SignalRHelper'

// import 'script-loader!jquery/dist/jquery.js'
import 'script-loader!abp-web-resources/Abp/Framework/scripts/abp.js'
import 'script-loader!abp-web-resources/Abp/Framework/scripts/libs/abp.jquery.js'
import AppConsts from '@/vendor/abp/appconst'
// import '@/libs/abp.js'
// import 'script-loader!@aspnet/signalr/dist/browser/signalr.js'

import 'famfamfam-flags/dist/sprite/famfamfam-flags.css'

import * as filters from './filters' // global filters

console.log(1, process.env)

// register global utility filters
Object.keys(filters).forEach(key => {
  Vue.filter(key, filters[key])
})

const locateMap = {
  en: enLocale,
  'zh-Hans': zhLocale
}

if (!abp.utils.getCookieValue('Abp.Localization.CultureName')) {
  var language = navigator.language
  language = language.replace('zh-CN', 'zh-Hans') // abp多语言里中文的标识不一样
  abp.utils.setCookieValue(
    'Abp.Localization.CultureName',
    language,
    new Date(new Date().getTime() + 5 * 365 * 86400000),
    abp.appPath
  )
}

/**
 * If you don't want to use mock-server
 * you want to use mockjs for request interception
 * you can execute:
 *
 * import { mockXHR } from '../mock'
 * mockXHR()
 */

// set ElementUI lang to EN
// Vue.use(ElementUI, { locale })
Vue.use(ELEMENT, {
  locale: locateMap[abp.utils.getCookieValue('Abp.Localization.CultureName')]
})

Vue.config.productionTip = false

// Promise.all([
//   store.dispatch({
//     type: 'session/getAbpUserConfiguration'
//   }),
//   store.dispatch({
//     type: 'session/init'
//   })
// ])
store
  .dispatch({
    type: 'session/getAbpUserConfiguration'
  })
  .then(async results => {
    const data = results
    // 拓展abp对象
    window.abp = extend(true, abp, data.data.result)

    await store.dispatch({ type: 'session/init' })

    Vue.prototype.L = function(text, source, ...args) {
      source = source || AppConsts.localization.defaultLocalizationSourceName
      let localizedText = window.abp.localization.localize(
        text,
        AppConsts.localization.defaultLocalizationSourceName
      )
      if (!localizedText) {
        localizedText = text
      }
      if (!args || !args.length) {
        return localizedText
      }
      args.unshift(localizedText)
      return abp.utils.formatString.apply(this, args)
    }

    // generate accessible routes map based on roles
    const accessRoutes = await store.dispatch('permission/generateRoutes')
    console.log(1, accessRoutes)
    // dynamically add accessible routes
    router.options.routes.push.apply(router.options.routes, accessRoutes)
    router.addRoutes(accessRoutes)

    new Vue({
      el: '#app',
      router,
      store,
      async mounted() {
        if (
          this.$store.state.session.user
          //  && JSON.parse(
          //   this.$store.state.session.application.features['SignalR'].value
          // )
        ) {
          // if (JSON.parse(this.$store.state.session.application.features['SignalR.AspNetCore'].value)) {
          SignalRAspNetCoreHelper.initSignalR()
          var notifyTypes = ['info', 'success', 'warning', 'error', 'error']

          abp.event.on('abp.notifications.received', userNotification => {
            var notif = userNotification.notification
            // console.log(notif)
            this.$notify({
              type: notifyTypes[notif.severity],
              title: notif.data.message,
              message: parseTime(notif.creationTime),
              position: 'bottom-right'
            })
            store.dispatch({ type: 'notification/getTop3' })
            // abp.notifications.showUiNotifyForUserNotification(userNotification)
          })

          // }
          /*
          var chatHub = null

          abp.signalr
            .startConnection(
              AppConsts.remoteServiceBaseUrl + '/signalr-myChatHub',
              function(connection) {
                chatHub = connection // Save a reference to the hub

                connection.on('getMessage', function(message) {
                  // Register for incoming messages
                  console.log('received message: ' + message)
                })
              }
            )
            .then(function(connection) {
              abp.log.debug('Connected to myChatHub server!')
              abp.event.trigger('myChatHub.connected')
            })

          abp.event.on('myChatHub.connected', function() {
            // Register for connect event
            chatHub.invoke(
              'sendMessage',
              "Hi everybody, I'm connected to the chat!"
            ) // Send a message to the server
          }) */
        }

        // Display a list of open pages
        // this.$store.commit('setOpenedList')
        // this.$store.commit('initCachepage')
      },
      async created() {
        abp.message.info = message => {
          this.$message(message)
        }

        abp.message.success = message => {
          this.$message({
            message: message,
            type: 'success'
          })
        }

        abp.message.warn = message => {
          this.$message({
            message: message,
            type: 'warning'
          })
        }

        abp.message.error = message => {
          this.$message.error(message)
        }

        abp.message.confirm = (message, titleOrCallback, callback) => {
          this.$confirm(message, titleOrCallback)
        }

        abp.notify.success = (message, title, options) => {
          this.$notify({
            title: title,
            message: message,
            type: 'success'
          })
        }

        abp.notify.info = (message, title, options) => {
          this.$notify({
            title: title,
            message: message,
            type: 'warning'
          })
        }

        abp.notify.warn = (message, title, options) => {
          this.$notify.info({
            title: title,
            message: message
          })
        }

        abp.notify.error = (message, title, options) => {
          this.$notify.error({
            title: title,
            message: message
          })
        }
      },
      render: h => h(App)
    })
  })
